package com.roadjava.demo03.util;


import com.roadjava.demo03.bean.UserInfo3;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class ValidationUtil3 {
    // 线程安全
    private static Validator validator;

    static {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    public static List<String> valid(UserInfo3 userInfo) {
        // 如果被校验对象userInfo没有校验通过，则set里面就有校验信息
        Set<ConstraintViolation<UserInfo3>> set = validator.validate(userInfo);
        List<String> list = set.stream().map(v ->
                        "属性：" + v.getPropertyPath()
                                + "，属性的值：" + v.getInvalidValue()
                                + "，消息模板：" + v.getMessageTemplate() // 消息模板：el表达式还没被解析成值的时候
                                + "，校验不通过的提示信息：" + v.getMessage())
                .collect(Collectors.toList());
        return list;
    }
}